package com.ibiaoke.boss.controller;

import com.alibaba.fastjson.JSONObject;
import com.ibiaoke.boss.service.RegisterService;
import com.ibiaoke.common.base.BaseController;
import com.ibiaoke.common.configs.GlobalConfigs;
import com.ibiaoke.common.configs.GlobalConfigsKey;
import com.ibiaoke.common.configs.WeChatConfigs;
import com.ibiaoke.common.consts.CommonConsts;
import com.ibiaoke.common.consts.WeChatConsts;
import com.ibiaoke.common.exception.ServiceException;
import com.ibiaoke.common.response.Res;
import com.ibiaoke.common.utils.HttpUtil;
import com.ibiaoke.common.utils.SmsUtil;
import com.ibiaoke.customer.entity.Customer;
import com.ibiaoke.customer.entity.ThirdPartLogin;
import com.ibiaoke.customer.service.CustomerService;
import com.ibiaoke.customer.service.ThirdPartLoginService;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.jdbc.Null;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.Date;
import java.util.Formatter;
import java.util.UUID;

/**
 * Created by biaoke on 2017/7/5.
 */
@Controller
public class WxWeChatController extends BaseController {

    @Autowired
    private ThirdPartLoginService thirdPartLoginService;

    @Autowired
    private CustomerService customerService;

    @Autowired
    private RegisterService registerService;

    /**
     * 用户登录
     */
    @RequestMapping("userVerify")
    public void userVerify() {
        //微信渠道
        String redirect_uri = GlobalConfigs.getConfigure(GlobalConfigsKey.WeChat.REDIRECT_URI);
        try {
            redirect_uri = URLEncoder.encode(redirect_uri, "utf-8");

            String url = "https://open.weixin.qq.com/connect/oauth2/authorize?" +
                    "appid=" + WeChatConfigs.getAppID() + "&redirect_uri=" + redirect_uri +
                    "&response_type=code&scope=snsapi_userinfo&state=91#wechat_redirect";
            getResponse().sendRedirect(url);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 验证成功之后调用该接口返回用户的openId并存入session中
     *
     * @param request
     * @param response
     */
    @RequestMapping("successRedirect")
    @ResponseBody
    public Res successRedirect(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        String code = request.getParameter("code");
        if (StringUtils.isNotBlank(code)) {
            StringBuilder url = new StringBuilder();
            url.append("https://api.weixin.qq.com/sns/oauth2/access_token?appid=");
            url.append(WeChatConfigs.getAppID());
            url.append("&secret=");
            url.append(WeChatConfigs.getAppSecret());
            url.append("&code=");
            url.append(code);
            url.append("&grant_type=authorization_code");
            String res = HttpUtil.httpClientGet(url.toString());
            //get weixin user's openid and access_token
            if (StringUtils.isNotBlank(res)) {
                JSONObject jsonObj = JSONObject.parseObject(res);
                if (jsonObj.containsKey(WeChatConsts.OPEN_ID)) {
                    String openid = jsonObj.getString(WeChatConsts.OPEN_ID);
                    String AccessToken = jsonObj.getString("access_token");
                    session.setAttribute("AccessToken", AccessToken);
                    //通过获取到的openid，获取昵称和头像，存表中
                    new Thread(()-> thirdPartLoginService.updateHeadPicAndNickName(openid, AccessToken)).start();
                    session.setAttribute(WeChatConsts.OPEN_ID, openid);
                    ThirdPartLogin thirdPartyLogin = thirdPartLoginService.getByUid(openid);
                    if (thirdPartyLogin != null) {
                        //通过手机号获取的user，放进session中
                        Customer customer = customerService.getCustomer(thirdPartyLogin.getMobile());
                        session.setAttribute(CommonConsts.LOGIN_SESSION_NAME, customer);
                    }
                }
            }
        }
        return Res.create();
    }


    /**
     * 调用微信JS-SDK所需要的参数
     *
     * @param request
     * @param response
     */
    @RequestMapping("createConfig")
    @ResponseBody
    public Res createConfig(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        Res res = Res.create();
        String url = request.getParameter("shareUrl");
        String rand = UUID.randomUUID().toString();  //随机字符串
        String timestamp = Long.toString(System.currentTimeMillis() / 1000);
        String signature = "";
        try {
            String string1 = "";
            string1 = "jsapi_ticket=" + WeChatConfigs.getJsapiTicket() +
                    "&noncestr=" + rand +
                    "&timestamp=" + timestamp +
                    "&url=" + url;
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(string1.getBytes("UTF-8"));
            signature = byteToHex(crypt.digest());
            res.addResponse("rand", rand);
            res.addResponse("sign", signature);
            res.addResponse("timestamp", timestamp);
            res.addResponse("appid", WeChatConfigs.getAppID());
            res.addResponse("url", url);
        } catch (Exception e) {
            throw new ServiceException("createConfig错误", e);
        }
        return res;
    }

    private String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }


    /**
     * 根据手机验证码登陆并綁定關係
     *
     * @param session
     * @param response
     * @param mobile
     * @param validate
     * @throws IOException
     */
    @RequestMapping(value = "/weixinBind.do")
    @ResponseBody
    public Res weixinBind(HttpSession session, HttpServletResponse response,
                          @RequestParam(value = "mobile") String mobile,
                          @RequestParam(value = "code") String validate
    ) {
        Customer user = customerService.getCustomer(mobile);
        SmsUtil.validateMobileCode(mobile,validate);
        if (user == null) {
            user = new Customer();
            user.setCustomerMobile(mobile);
            registerService.createNewCustomer(mobile, null);
            user = customerService.getCustomer(mobile);

        }
        ThirdPartLogin thirdPartyLogin = new ThirdPartLogin();
        thirdPartyLogin.setMobile(mobile);
        thirdPartyLogin.setuId((String) session.getAttribute(WeChatConsts.OPEN_ID));
        thirdPartyLogin.setUserId(user.getCustomerId());
        thirdPartyLogin.setCreateTime(new Date());
        session.setAttribute(CommonConsts.LOGIN_SESSION_NAME, user);
        String  accessToken = getSession().getAttribute("AccessToken").toString();
        thirdPartLoginService.bind(thirdPartyLogin,accessToken);
        return new Res();

    }

}
